package com.qianli.cashmama.trade.unique.impl;

import com.alibaba.fastjson.JSON;
import com.fqgj.common.utils.DateUtil;
import com.qianli.cashmama.product.facade.result.ProductCategory;
import com.qianli.cashmama.trade.common.enums.UniqueRepeatTypeEnum;
import com.qianli.cashmama.trade.common.enums.UniqueStatusEnum;
import com.qianli.cashmama.trade.dao.TPreventRepeatDao;
import com.qianli.cashmama.trade.domain.model.TradeBase;
import com.qianli.cashmama.trade.entity.TPreventRepeatEntity;
import com.qianli.cashmama.trade.integration.product.ProductIntegrationService;
import com.qianli.cashmama.trade.unique.TradeUniqueService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by scrack on 2017/7/21.
 */
@Service("tradeUniqueService")
public class TradeUniqueServiceImpl implements TradeUniqueService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TradeUniqueServiceImpl.class);

    @Autowired
    private TPreventRepeatDao preventRepeatDao;

    @Autowired
    private ProductIntegrationService productIntegrationService;

    @Override
    public UniqueStatusEnum uniqueDecide(TradeBase tradeBase) {

        //利用数据库的唯一性索引达到避免创建重复订单的目的
        TPreventRepeatEntity preventRepeatEntity = null;
        try {
            preventRepeatEntity = new TPreventRepeatEntity()
                    .setRepeatType(UniqueRepeatTypeEnum.CREATE_TRADE.getType())
                    .setTradeNo(tradeBase.getTradeNo())
                    .setUserCode(tradeBase.getUserCode())
                    .setMerchantCode(tradeBase.getMerchantCode())
                    .setProductCategory(tradeBase.getProductCategory())
                    .setRepeatVersion("0");
            preventRepeatDao.insert(preventRepeatEntity);
            return UniqueStatusEnum.NEW;
        } catch (DuplicateKeyException e) {
            LOGGER.error("== 重复创建订单 ==,userCode:{}, errorMsg:{}", JSON.toJSONString(preventRepeatEntity), e.getMessage());
            return UniqueStatusEnum.EXIST;
        }
    }


    @Override
    public UniqueStatusEnum uniqueDecideByType(String categoryCode, String tradeNo, String userCode, Integer eventType) {
        ProductCategory productCategory = productIntegrationService.getCategoryByCode(categoryCode);

        //利用数据库的唯一性索引达到避免创建重复订单的目的
        TPreventRepeatEntity preventRepeatEntity = null;
        try {
            preventRepeatEntity = new TPreventRepeatEntity()
                    .setRepeatType(eventType)
                    .setTradeNo(tradeNo)
                    .setUserCode(userCode)
                    .setMerchantCode(productCategory.getMerchantCode())
                    .setProductCategory(categoryCode)
                    .setRepeatVersion("0");
            preventRepeatDao.insert(preventRepeatEntity);
            return UniqueStatusEnum.NEW;
        } catch (DuplicateKeyException e) {
            LOGGER.error("== 重复创建订单 ==,userCode:{}, errorMsg:{}", JSON.toJSONString(preventRepeatEntity), e.getMessage());
            return UniqueStatusEnum.EXIST;
        }
    }

    @Override
    public boolean releaseUniqueLock(String userCode, String categoryCode, String tradeNo, Integer type) {
        try {
            Map<String, Object> paramMap = new HashMap();
            paramMap.put("userCode", userCode);
            paramMap.put("repeatType", type);
            paramMap.put("productCategory", categoryCode);
            TPreventRepeatEntity preventRepeatEntity = preventRepeatDao.selectOneByParam(paramMap);
            if (preventRepeatEntity != null) {
                preventRepeatEntity.setRepeatVersion(String.valueOf(DateUtil.getMillis()));
                preventRepeatDao.updateRepeatVersion(preventRepeatEntity);
            }
            LOGGER.info("== 释放交易唯一锁成功 ==,userCode:{},tradeNo:{}", userCode, tradeNo);
            return true;
        } catch (Exception e) {
            LOGGER.error("== 释放交易唯一锁失败 ==,userCode:{},tradeNo:{},e:", userCode, tradeNo, e);
            return false;
        }
    }

    @Override
    public boolean releaseUniqueLock(TradeBase tradebase) {
        try {
            Map<String, Object> paramMap = new HashMap();
            paramMap.put("userCode", tradebase.getUserCode());
            paramMap.put("repeatType", UniqueRepeatTypeEnum.CREATE_TRADE.getType());
            paramMap.put("merchantCode", tradebase.getMerchantCode());
            TPreventRepeatEntity preventRepeatEntity = preventRepeatDao.selectOneByParam(paramMap);
            if (preventRepeatEntity != null) {
                preventRepeatEntity.setRepeatVersion(String.valueOf(DateUtil.getMillis()));
                preventRepeatDao.updateRepeatVersion(preventRepeatEntity);
            }
            LOGGER.info("== 释放交易唯一锁成功 ==,userCode:{},tradeNo:{}", tradebase.getUserCode(), tradebase.getTradeNo());
            return true;
        } catch (Exception e) {
            LOGGER.error("== 释放交易唯一锁失败 ==,userCode:{},tradeNo:{},e:", tradebase.getUserCode(), tradebase.getTradeNo(), e);
            return false;
        }
    }
}
